package com.douxg.learning.springboot.base.aop;

import cn.hutool.core.util.StrUtil;
import com.douxg.learning.springboot.base.util.UnitConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author douxg
 * @date 2022/7/26
 */
@Component
@Aspect
@Order(2)
@Slf4j
public class AopOrder {
    @Around("@annotation(com.douxg.learning.springboot.base.aop.Runtime)")
    public Object runtime(ProceedingJoinPoint joinpoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
        Method method = methodSignature.getMethod();
        Runtime annotation = method.getAnnotation(Runtime.class);
        String name = "";
        if (annotation != null) {
            name = annotation.name();
        }
        if (StrUtil.isEmpty(name)) {
            String simpleName = joinpoint.getTarget().getClass().getSimpleName();
            String methodName = joinpoint.getSignature().getName();
            name = simpleName + "." + methodName;
        }
        long startTime = System.currentTimeMillis();
        Object result = joinpoint.proceed();
        long endTime = System.currentTimeMillis();

        String runTime = UnitConvertUtils.convertDate(endTime - startTime);
        log.info(name + "耗时：" + runTime);
        return result;
    }
}
